import 'package:awesome_project/gen/colors.gen.dart';
import 'package:awesome_project/providers/export_providers.dart';
import 'package:awesome_project/route/app_router.dart';
import 'package:awesome_project/utils/dialog_utils.dart';
import 'package:awesome_project/utils/ext/build_context_ext.dart';
import 'package:awesome_project/utils/strings.dart';
import 'package:awesome_project/widgets/asyncvalue_widget.dart';
import 'package:awesome_project/widgets/gaps.dart';
import 'package:awesome_project/widgets/load_more_child.dart';
import 'package:awesome_project/widgets/round_widget.dart';
import 'package:awesome_project/widgets/text_button_icon_x.dart';
import 'package:awesome_project/widgets/three_selector_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../models/data_models.dart';
import '../widgets/simple_widget.dart';

class MainPage extends HookConsumerWidget {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context, ref) {
    final vn = useValueNotifier(false);
    final vn2 = useValueNotifier("");
    final index1 = useRef(14);
    final index2 = useRef(14);
    final areaStr = useValueNotifier("山东省 滨州市");
    final categoryS = useRef([
      "类别1",
      "类别2",
      "类别3",
    ]);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('涉税专业服务机构', style: TextStyle(color: Colors.black)),
      ),
      body: Column(
        children: [
          ListTile(
            onTap: () {
              DialogUtils.showBottomWidget(
                  context,
                  TwoSelectorWidget(
                    index1: index1.value,
                    index2: index2.value,
                    onChange: (index11, index22, cityS) {
                      index1.value = index11;
                      index2.value = index22;
                      print("index11=$index11==index22=$index22");
                      areaStr.value =
                          "${cityS[index11].name} ${cityS[index11].children[index22].name}";
                    },
                  ));
            },
            leading: Text(
              "地区",
              style: context.textTheme.titleMedium,
            ),
            title: ValueListenableBuilder(
                valueListenable: areaStr,
                builder: (BuildContext context, String value, Widget? child) {
                  return Text(value);
                }),
            trailing: const Icon(Icons.arrow_forward_ios,
                size: 16, color: Colors.grey),
          ),
          const MyDivider(),
          const Gap.v(10),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: SizedBox(
                      height: 35,
                      child: TextField(
                        textAlignVertical: TextAlignVertical.center,
                        onTapOutside: (e) {
                          FocusManager.instance.primaryFocus?.unfocus();
                        },
                        decoration: InputDecoration(
                            isCollapsed: true,
                            prefixIcon: const Icon(
                              Icons.search,
                              color: Colors.grey,
                            ),
                            contentPadding:
                                const EdgeInsets.symmetric(horizontal: 10),
                            hintText: "请输入机构名字",
                            hintStyle: context.textTheme.bodyMedium
                                ?.copyWith(color: Colors.grey),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5),
                              borderSide: BorderSide.none,
                            ),
                            fillColor: ColorName.bgGray,
                            filled: true),
                      ),
                    ),
                  ),
                ),
                ElevatedButton(
                    onPressed: () {
                      appRouter.push(RoutePath.areaListPage);
                    },
                    child: const Text("搜索"))
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              ValueListenableBuilder(
                builder: (context, v, c) {
                  return TextButtonWithIconX(
                      isPre: false,
                      label: Text(v ? "信用积分降序" : "信用积分升序"),
                      style:
                          TextButton.styleFrom(foregroundColor: Colors.black),
                      onPressed: () {
                        vn.value = !vn.value;
                        ref.invalidate(organizationListProvider(
                            type: vn.value ? 0 : 1, category: vn2.value));
                      },
                      icon: Icon(
                          !v ? Icons.arrow_drop_down : Icons.arrow_drop_up));
                },
                valueListenable: vn,
              ),
              ValueListenableBuilder(
                  valueListenable: vn2,
                  builder: (context, v, c) {
                    return MenuAnchor(
                      style: MenuStyle(
                          backgroundColor:
                              WidgetStateProperty.all(Colors.white)),
                      builder: (context, controller, child) {
                        return TextButtonWithIconX(
                            isPre: false,
                            label: Text(isNotBlank(v) ? v : "机构类别"),
                            style: TextButton.styleFrom(
                                padding: EdgeInsets.zero,
                                foregroundColor: Colors.black),
                            onPressed: () {
                              if (controller.isOpen) {
                                controller.close();
                              } else {
                                controller.open();
                              }
                            },
                            icon: const Icon(Icons.arrow_drop_down));
                      },
                      menuChildren: categoryS.value
                          .map((e) => MenuItemButton(
                                style: MenuItemButton.styleFrom(
                                    foregroundColor:
                                        e == v ? Colors.blue : Colors.black),
                                child: Text(e),
                                onPressed: () {
                                  vn2.value = e;
                                },
                              ))
                          .toList(),
                    );
                  }),
            ],
          ),
          const MyDivider(),
          ColoredBox(
            color: ColorName.bgGray,
            child: Align(
                alignment: Alignment.centerRight,
                child: SizedBox(
                  height: 35,
                  child: TextButton(
                      style: TextButton.styleFrom(
                          padding: const EdgeInsets.only(right: 15),
                          textStyle: context.textTheme.labelMedium,
                          foregroundColor: Colors.grey),
                      onPressed: () {},
                      child: const Text("查看信用积分评价规则 >")),
                )),
          ),
          Expanded(
            child: RefreshIndicator(
              onRefresh: () => ref.refresh(organizationListProvider(
                      type: vn.value ? 0 : 1, category: vn2.value)
                  .future),
              child: AsyncValueWidget(
                ref.watch(organizationListProvider(
                    type: vn.value ? 0 : 1, category: vn2.value)),
                asyncValueBuilder: (value) {
                  final items = value?.list ?? [];
                  return LoadMoreChild(
                    hasMore: value?.hasMore ?? false,
                    loadMore: () => ref
                        .read(organizationListProvider(
                                type: vn.value ? 0 : 1, category: vn2.value)
                            .notifier)
                        .loadMore(),
                    child: ListView.separated(
                      itemBuilder: (BuildContext context, int index) {
                        return ServiceOrganizationCard(item: items[index]);
                      },
                      separatorBuilder: (BuildContext context, int index) {
                        return const MyDivider();
                      },
                      itemCount: items.length,
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class ServiceOrganizationCard extends StatelessWidget {
  final OrganizationModel item;

  const ServiceOrganizationCard({super.key, required this.item});

  @override
  Widget build(BuildContext context) {
    return RoundWidget(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(item.name,
                      style: const TextStyle(
                          fontSize: 14, fontWeight: FontWeight.bold)),
                ),
                ElevatedButton(
                  onPressed: () {},
                  child: const Text('我要委托'),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text('${item.score}分',
                style: const TextStyle(
                    fontSize: 18,
                    color: Colors.orange,
                    fontWeight: FontWeight.bold)),
            const Gap.v(8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InfoItem('机构人员数', '${item.staffCount}人'),
                InfoItem('当年服务户数', '${item.customerCount}户'),
              ],
            ),
            const Gap.v(8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InfoItem('当前服务自然人数', '${item.naturalPersonCount}人'),
                InfoItem('成立时间', item.establishDate),
              ],
            ),
            const Gap.v(8),
            Text('法定代表人：${item.legalRepresentative}'),
            if (item.address.isNotEmpty) Text('注册地址：${item.address}'),
          ],
        ),
      ),
    );
  }
}

class InfoItem extends StatelessWidget {
  final String label;
  final String value;

  const InfoItem(this.label, this.value);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(fontSize: 12, color: Colors.grey)),
        Text(value, style: const TextStyle(fontSize: 14)),
      ],
    );
  }
}
